#!/usr/bin/env node

const { Client } = require('pg');
const sqlite3 = require('sqlite3').verbose();
const path = require('path');

// PostgreSQL connection configuration
const pgConfig = {
  host: 'localhost',
  port: 15432,
  user: 'postgres',
  password: 'qwe!@#',
  database: 'Eng'
};

// SQLite database path
const sqliteDbPath = path.join(__dirname, '../resources/db/db.database');

async function importIelstWords() {
  console.log('Starting import of IELST words...');
  
  // Connect to PostgreSQL
  const pgClient = new Client(pgConfig);
  
  try {
    await pgClient.connect();
    console.log('Connected to PostgreSQL database');
    
    // Query words where ielst = 'YES'
    const res = await pgClient.query('SELECT word FROM enwords WHERE ielst = $1', ['YES']);
    console.log(`Found ${res.rows.length} words with ielst = 'YES'`);
    
    // Connect to SQLite database
    const sqliteDb = new sqlite3.Database(sqliteDbPath);
    
    // Create ielst_words table if it doesn't exist
    sqliteDb.serialize(() => {
      sqliteDb.run(`CREATE TABLE IF NOT EXISTS ielst_words (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        word TEXT UNIQUE NOT NULL
      )`);
      
      // Insert words into SQLite database
      const stmt = sqliteDb.prepare('INSERT OR IGNORE INTO ielst_words (word) VALUES (?)');
      
      let insertedCount = 0;
      res.rows.forEach(row => {
        stmt.run(row.word);
        insertedCount++;
      });
      
      stmt.finalize();
      
      console.log(`Successfully inserted ${insertedCount} words into ielst_words table`);
    });
    
    sqliteDb.close();
    
  } catch (err) {
    console.error('Error during import:', err);
  } finally {
    await pgClient.end();
    console.log('Disconnected from PostgreSQL database');
  }
}

// Run the import function
importIelstWords();